<?php

namespace app\controller\Api\V1\Client;

use app\helper\GetProductInfo;
use app\model\GameAuthorization;
use app\model\GameLogoConfig;
use app\model\LanderRecord;
use app\model\LanderVersion;
use app\request\Config;
use Exception;
use support\Request;
use support\Response;

class ConfigController
{

    protected \App\Helper\Config $configRe;
    protected GetProductInfo $getProductRe;


    public function __construct()
    {
        $this->configRe = \app\helper\Config::getInstance();
        $this->getProductRe = GetProductInfo::getInstance();
    }


    /**
     * 获取游戏配置文件信息
     *
     * @param Request $request
     * @return Response
     * @throws Exception
     */
    public function Generate(Request $request): Response
    {

        $validate = new Config();

        if (!$validate->scene('generate')->check($request->all())) {
            throw new Exception($validate->getError(), 500);
        }

        if ($request->input('release_type') != 1 || $request->input('game') == 0) {
            return jsonRe([
                'info' => [],
            ]);
        }

        $gameInfo = GameAuthorization::query()->where('ulid', $request->input('game'))->where('state', 1)->first();
        if (!$gameInfo) {
            throw new Exception('游戏不存在', 500);
        }

        $merchantPlatformInfo = $this->getProductRe->GetMerchantPlatform();
        $pushPlatformInfo = $this->getProductRe->GetPushPlatform();
        $publicPlatformInfo = $this->getProductRe->GetPublicPlatform();
        $boxPlatformInfo = $this->getProductRe->GetBoxPlatform();

        $landerRecordInfo = LanderRecord::query()->where('game', $request->input('game'))
            ->where('product', $merchantPlatformInfo['ulid'])->where('state', 2)->first();
        if (!$landerRecordInfo) {
            throw new Exception('登录器生成记录不存在', 500);
        }
        $landerRecordInfo = $landerRecordInfo->toArray();

        $landerVersionInfo = LanderVersion::query()->where('ulid', $landerRecordInfo['lander_version'])
            ->where('package_type', 1)->first();
        if (!$landerVersionInfo) {
            throw new Exception('登录器版本不存在', 500);
        }
        $landerVersionInfo = $landerVersionInfo->toArray();

        $gameLogoInfo = GameLogoConfig::query()->where('merchant', $gameInfo->merchant)
            ->where('game', $request->input('game'))->first();

        if ($this->configRe->Get('use_cloud_storage')) {
            $appConfig = [
                'APP_CONFIG1' => $this->configRe->Get('aliyun_oss_domain') . '/game-area-list/config/server/' . $gameInfo->merchant . '_' . $request->input('game') . '.txt',
                'APP_CONFIG2' => $this->configRe->Get('tencent_cloud_cos_domain') . '/game-area-list/config/server/' . $gameInfo->merchant . '_' . $request->input('game') . '.txt',
            ];

            if ($this->configRe->Get('cloud_storage_driver') === 'tencent') {
                $configFileUrl = $this->configRe->Get('tencent_cloud_cos_domain') . '/config.txt';
            } else {
                $configFileUrl = $this->configRe->Get('qiniu_kodo_domain') . '/config.txt';
            }
        } else {
            $appConfig = [
                'APP_CONFIG1' => $pushPlatformInfo['api_url'] . '/game-area-list/config/server/' . $gameInfo->merchant . '_' . $request->input('game') . '.txt',
                'APP_CONFIG2' => $pushPlatformInfo['api_url'] . '/game-area-list/config/server/' . $gameInfo->merchant . '_' . $request->input('game') . '.txt',
            ];
            $configFileUrl = $pushPlatformInfo['api_url'] . '/config.txt';
        }

        $data = [
            'MCH_ID' => $gameInfo->merchant,  // mac_id 商户ID

            'GAME_ID' => $request->input('game'),  // game_id 游戏ID
            'ANDROID_LABEL' => $gameInfo->title,  // android_label 游戏名称
            'GAME_ICON' => $gameLogoInfo ? json_decode($gameLogoInfo->logo) : [],  // game_icon 游戏图标

            'PACKAGE' => 'com.biqi2.game',  // package 包名
            'MOTHER_PACK' => $landerVersionInfo['package_name'],  // mother_pack 母包的版本号
            'LANDER_VERSION' => $landerRecordInfo['lander_version'],  // lander_version 登陆器版本号
            'OPEN_ID' => 0,  // open_id 开发者ID REALEASE_TYPE为1传0
            'GAME_TYPE' => $landerVersionInfo['game_type'],  // game_type 游戏类型
            'PROMOTION_PLATFORM' => $landerVersionInfo['package_platform'],  // promotion_platform 0表示pc 1表示android 2表示ios 3表示h5
            'RELEASE_TYPE' => 1,  // release_type 0 工具服测试  1 表示正式
            'PROMOTION_PACKID' => $landerVersionInfo['package_id'] ?? 0,  // promotion_packid 包id(PROMOTION_PLATFORM为1或2时才有)
            'CHANNEL_ID' => 0,  // channel_id 渠道id
            'CHANNEL_NAME' => 0,  // channel_name 渠道名称
            'PROMOTION_USERID' => 0,  // promotion_userid 推广员id
            'PROMOTION_LEVEL' => 0,  // promotion_level 推广员等级(0不是推广员 1一级推广员  2二级推广员)
            'THIRD_PARTY' => '[]',  // third_party 第三方平台(0无 1巨量 2快手 3百度 4广点通 5友盟)
            'APP_ID' => 0,  // add_id 巨量或快手的APP id
            'APP_NAME' => 0,  // app_name 巨量的APP英文名称 快手的中文名称
            'APP_CHANNEL' => 0,  // app_channel 快手app 渠道id
            'APP_SECRET_KEY' => 0,  // app_secret_key 广点通的key
            'USER_ACTION_SET_ID' => 0,  // user_action_set_id 广点通的自定义id
            'UAPP_KEY' => 0,  // uapp_key 友盟key
            'UAPP_CHANNEL' => 0,  // uapp_channel 友盟app的渠道id

            'DOUYIN_APP_ID' => 0,
            'KUAISHOU_APP_ID' => 0,
            'KUAISHOU_APP_NAME' => '',

            'UPDATE_API_URL' => '',
            'APP_CONFIG' => $appConfig,  // 静态对象存储文件请求，UPDATE_API_URL字段需为空
            'BOX_SDK_URL' => $boxPlatformInfo['api_url'] ?? '',
            'PUB_API_URL' => $publicPlatformInfo['api_url'] ?? '',
            'CONFIG_FILE_URL' => $configFileUrl,
        ];

        return jsonRe([
            'info' => $data,
        ]);

    }


    /**
     * 获取日志配置
     *
     * @param Request $request
     * @return Response
     */
    public function Log(Request $request): Response
    {

        return jsonRe([
            'state' => $this->configRe->Get('game_log_state', true) == true,
            'logmaxsize' => $this->configRe->Get('game_log_max_size', 10),
            'logsavedays' => $this->configRe->Get('game_log_storage_days', 1),
            'outiointernal' => $this->configRe->Get('game_log_output_frequency', 100),
            'packsize' => $this->configRe->Get('game_log_package_threshold', 0),
            'allowlog' => $this->configRe->Get('game_log_output_filter'),
            'posttomanager' => '',
            'needpackmore' => $this->configRe->Get('game_log_package_threshold', 0) > 0
        ]);

    }

}